package com.zhenhunfan.io.model.bio.demo01;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p>Title: BioServerSingle</p>
 * <p>Description: </p>
 *
 * @author zhenhunfan
 * @version 1.0.0
 * @date 2021/3/31
 */
public class BioServerSingle {
    public static void main(String[] args) {
        int port = 8080;
        ServerSocket serverSocket = null;//服务端
        Socket socket = null;
        InputStream in = null;
        OutputStream out = null;
        try{
            serverSocket = new ServerSocket(port);//指定端口
            while(true){
                System.out.println("start");
                socket = serverSocket.accept();//阻塞,没有请求时就一直阻塞在这儿
                in = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int length = 0;
                while ((length = in.read(buffer))>0){//阻塞，有请求但没有数据时就一直阻塞在这儿
                    System.out.println("input is:" + new String(buffer,0,length));
                    out = socket.getOutputStream();
                    out.write("success".getBytes());
                    System.out.println("end");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
